package com.zbc.interceptor;

import com.zbc.constant.JwtClaimsConstant;
import com.zbc.context.BaseContext;
import com.zbc.properties.JwtProperties;
import com.zbc.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthVerifyAdminInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    public AuthVerifyAdminInterceptor(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        String token = request.getHeader(jwtProperties.getAdminTokenName());
        try{
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(),token);
            Integer empId = (Integer) claims.get(JwtClaimsConstant.EMP_ID);
            BaseContext.setCurrentId(empId);
            return true;
        }catch (Exception ex) {
            response.setStatus(401);
            return false;
        }
    }
}
